package com.problemproject.dome.viewpager;

import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.ViewPager;

import android.os.Bundle;

import com.google.android.material.tabs.TabLayout;
import com.problemproject.dome.R;

import java.util.ArrayList;
import java.util.List;

/**
 * ViewPagerFragmentActivity
 * viewpager+tablayout +fragment (fragment 复用 多个fragment后 fragment 数据重复加载 )
 * @author huo
 * @date 2022/4/2 下午 03:53
 */
public class ViewPagerFragmentActivity extends AppCompatActivity {
    private TabLayout tabLayout;
    private ViewPager viewPage;
    private List<Fragment> fragments = new ArrayList<>();
    private String titles[] =  {"最新", "热门", "我的","测试","数据","预加载"};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_view_pager_fragment);
        initView();
        for (int i = 0; i < titles.length; i++) {
            fragments.add(TabFragment.getInstance(titles[i]));
            tabLayout.addTab(tabLayout.newTab());
        }


        tabLayout.setupWithViewPager(viewPage,false);
        ViewPageAdapter viewPageAdapter = new ViewPageAdapter(getSupportFragmentManager(), fragments,titles);
        viewPage.setAdapter(viewPageAdapter);
        viewPage.setOffscreenPageLimit(2);
    }

    private void initView() {
        tabLayout = (TabLayout) findViewById(R.id.tabLayout);
        viewPage = (ViewPager) findViewById(R.id.viewPage);
    }
}